package com.tupu.service.impl.dispatch;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tupu.entity.dispatch.*;
import com.tupu.mapper.dispatch.*;
import com.tupu.service.dispatch.DadsDdrzService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * (VDadsDdrz)表服务实现类
 *
 * @author makejava
 * @since 2023-11-16 16:42:12
 */
@Service("vDacsDdrzService")
public class DadsDdrzServiceImpl implements DadsDdrzService {
    @Resource
    private VDadsDdrzMapper vDacsDdrzMapper;
    @Resource
    private DadsDdrzMapper dadsDdrzMapper;
    @Resource
    private DadsJxdMapper dadsJxdMapper;
    @Resource
    private DadsFsdgdMapper dadsFsdgdMapper;
    @Resource
    private DadsJxjhMapper dadsJxjhMapper;
    @Resource
    private DadsSbqxMapper dadsSbqxMapper;

    @Resource
    private DadsJxczbwxlMapper dadsJxczbwxlMapper;

    @Resource
    private DadsJwfxMapper dadsJwfxMapper;


    @Override
    @DS("dfdz")
    public Page<VDadsDdrz> queryVDacsDdrzPage(QueryDdrzParmas params, Integer pageNum, Integer pageSize) {
/*        QueryWrapper queryWrapper = new QueryWrapper();
        if (!StrUtil.isEmpty(params.getStation())) {
            queryWrapper.eq("station", params.getStation());
        }
        if (!StrUtil.isEmpty(params.getGznr())) {
            queryWrapper.like("ycqk", params.getGznr());
        }
        if (ObjectUtil.isNotEmpty(params.getStartDate()) && ObjectUtil.isNotEmpty(params.getEndDate())) {
            queryWrapper.ge("jlsj", params.getStartDate() + " 00:00:00");
            queryWrapper.le("jlsj", params.getEndDate() + " 23:59:59");
        }
        if (!StrUtil.isEmpty(params.getSbmc())) {
            queryWrapper.like("sbmc", params.getSbmc());
        }
        queryWrapper.orderByDesc("jlsj");*/
        Page<VDadsDdrz> page = new Page<>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);

        //Page<VDadsDdrz> vDacsDdrzPage = vDacsDdrzMapper.selectPage(page, queryWrapper);
        String station = params.getStation();
        if (StringUtils.isEmpty(station)) {
            station = "";
        }
        String ycqk = params.getGznr();
        if (StringUtils.isEmpty(ycqk)) {
            ycqk = "";
        }
        String startDate = params.getStartDate();
        if (StringUtils.isEmpty(startDate)) {
            startDate = "";
        }
        String endDate = params.getEndDate();
        if (StringUtils.isEmpty(endDate)) {
            endDate = "";
        }
        String sbmc = params.getSbmc();
        if (StringUtils.isEmpty(sbmc)) {
            sbmc = "";
        }

        Page<VDadsDdrz> vDacsDdrzPage = dadsDdrzMapper.getVDadsDdrzByPage(page, station, ycqk, startDate, endDate, sbmc);
        for (VDadsDdrz record : vDacsDdrzPage.getRecords()) {
            if (StrUtil.isEmpty(record.getYcqk())) {
                continue;
            }
            String clqk = record.getYcqk();
            record.setClqk("");
            int index = -1;
            if (record.getDdrzlx().equals("交流线路跳闸") || record.getDdrzlx().equals("交流线路跳闸上级单位")) {
                index = record.getYcqk().indexOf("巡线结果");
            } else if (record.getDdrzlx().equals("异常信号处理")) {
                index = record.getYcqk().indexOf("处理结果");
            } else if (record.getDdrzlx().equals("设备缺陷")) {
                index = record.getYcqk().indexOf("处理情况");
            }
            if (index > -1) {
                record.setYcqk(clqk.substring(0, index));
                record.setClqk(clqk.substring(index, clqk.length()));
            }
        }
        return vDacsDdrzPage;
    }

    @Override
    @DS("dfdz")
    public Page<HistoryList> queryHistoryJxd(QueryDdrzParmas queryDdrzParmas) {
        if (StrUtil.isEmpty(queryDdrzParmas.getSbmc())) {
            throw new RuntimeException("设备名称不能为空！");
        }
        Page<HistoryList> page = new Page<>(queryDdrzParmas.getPage(), queryDdrzParmas.getSize());
        queryDdrzParmas.getSbmc();
        Page<HistoryList> historyJxdPage1 = dadsDdrzMapper.getHistoryJxd(page, queryDdrzParmas.getSbmc(), queryDdrzParmas.getStation());
        return historyJxdPage1;
    }

    @Override
    @DS("dfdz")
    public DadsJxdResult queryDadsJxdById(String listId) {
        //QueryWrapper queryWrapper = new QueryWrapper();
        //queryWrapper.eq("jxd_id", listId);
        //DadsJxd dadsJxd = dadsJxdMapper.selectOne(queryWrapper);
        DadsJxd dadsJxd = dadsJxdMapper.selectById(listId);

        if (ObjectUtil.isEmpty(dadsJxd)) {
            throw new RuntimeException("查询检修单信息失败！未查询到检修单信息");
        }
        DadsJxdResult dadsJxdResult = new DadsJxdResult();
        BeanUtils.copyProperties(dadsJxd, dadsJxdResult);
        if (ObjectUtil.isNotEmpty(dadsJxd.getPzgzkssj()) && ObjectUtil.isNotEmpty(dadsJxd.getPzgzjssj())) {
            Long dateSub = DateUtil.between(dadsJxd.getPzgzjssj(), dadsJxd.getPzgzkssj(), DateUnit.HOUR);
            dateSub += 1;
            dateSub = 24 * dateSub;
            dadsJxdResult.setPzgzsc(dateSub);
        }
        if (ObjectUtil.isNotEmpty(dadsJxd.getXkTdksSj()) && ObjectUtil.isNotEmpty(dadsJxd.getXkTdjsSj())) {
            Long dateSub = DateUtil.between(dadsJxd.getXkTdjsSj(), dadsJxd.getXkTdksSj(), DateUnit.HOUR);
            dateSub += 1;
            dateSub = 24 * dateSub;
            dadsJxdResult.setPzgzsc(dateSub);
        }
        String[] yjArr = null;
        // 方式意见
        if (StrUtil.isNotEmpty(dadsJxd.getFsyj())) {
            yjArr = dadsJxd.getFsyj().split(";");
            dadsJxdResult.setFsqfyj(yjArr[0]);
            dadsJxdResult.setFsqfr(yjArr[1]);
            StringBuilder stringBuilder = new StringBuilder(yjArr[2]);
            stringBuilder.insert(10, " ");
            dadsJxdResult.setFsqfsj(stringBuilder.toString());
        }
        // 安自意见
        if (StrUtil.isNotEmpty(dadsJxd.getAzyj())) {
            yjArr = dadsJxd.getAzyj().split(";");
            dadsJxdResult.setAzqfyj(yjArr[0]);
            dadsJxdResult.setAzqfr(yjArr[1]);
            StringBuilder stringBuilder = new StringBuilder(yjArr[2]);
            stringBuilder.insert(10, " ");
            dadsJxdResult.setAzqfsj(stringBuilder.toString());
        }
        // 保护意见
        if (StrUtil.isNotEmpty(dadsJxd.getBhyj())) {
            yjArr = dadsJxd.getBhyj().split(";");
            dadsJxdResult.setBhqfyj(yjArr[0]);
            dadsJxdResult.setBhqfr(yjArr[1]);
            StringBuilder stringBuilder = new StringBuilder(yjArr[2]);
            stringBuilder.insert(10, " ");
            dadsJxdResult.setBhqfsj(stringBuilder.toString());
        }
        // 通信意见
        if (StrUtil.isNotEmpty(dadsJxd.getTxyj())) {
            yjArr = dadsJxd.getTxyj().split(";");
            dadsJxdResult.setTxqfyj(yjArr[0]);
            dadsJxdResult.setTxqfr(yjArr[1]);
            StringBuilder stringBuilder = new StringBuilder(yjArr[2]);
            stringBuilder.insert(10, " ");
            dadsJxdResult.setTxqfsj(stringBuilder.toString());
        }
        // 自动化意见
        if (StrUtil.isNotEmpty(dadsJxd.getZdhyj())) {
            yjArr = dadsJxd.getZdhyj().split(";");
            dadsJxdResult.setZdhqfyj(yjArr[0]);
            dadsJxdResult.setZdhqfr(yjArr[1]);
            StringBuilder stringBuilder = new StringBuilder(yjArr[2]);
            stringBuilder.insert(10, " ");
            dadsJxdResult.setZdhqfsj(stringBuilder.toString());
        }
        // 水调意见
        if (StrUtil.isNotEmpty(dadsJxd.getSdyj())) {
            yjArr = dadsJxd.getSdyj().split(";");
            dadsJxdResult.setSdqfyj(yjArr[0]);
            dadsJxdResult.setSdqfr(yjArr[1]);
            StringBuilder stringBuilder = new StringBuilder(yjArr[2]);
            stringBuilder.insert(10, " ");
            dadsJxdResult.setSdqfsj(stringBuilder.toString());
        }
        // 调度意见
        if (StrUtil.isNotEmpty(dadsJxd.getDdyj())) {
            yjArr = dadsJxd.getDdyj().split(";");
            dadsJxdResult.setDdqfyj(yjArr[0]);
            dadsJxdResult.setDdqfr(yjArr[1]);
            StringBuilder stringBuilder = new StringBuilder(yjArr[2]);
            stringBuilder.insert(10, " ");
            dadsJxdResult.setDdqfsj(stringBuilder.toString());
        }
        // 相关单位意见
        if (StrUtil.isNotEmpty(dadsJxd.getXgddjgyj())) {
            yjArr = dadsJxd.getXgddjgyj().split(";");
            dadsJxdResult.setXgdwqfyj(yjArr[0]);
            dadsJxdResult.setXgdwqfr(yjArr[1]);
            StringBuilder stringBuilder = new StringBuilder(yjArr[2]);
            stringBuilder.insert(10, " ");
            dadsJxdResult.setXgdwqfsj(stringBuilder.toString());
        }

        return dadsJxdResult;
    }

    @Override
    @DS("dfdz")
    public Page<HistoryList> queryHistoryBgd(QueryDdrzParmas parmas) {
        if (StrUtil.isEmpty(parmas.getSbmc())) {
            throw new RuntimeException("设备名称不能为空！");
        }
        Page<HistoryList> page = new Page<>(parmas.getPage(), parmas.getSize());
        Page<HistoryList> historyJxdPage1 = dadsDdrzMapper.getHistoryBgd(page, parmas.getSbmc(), parmas.getStation());
        return historyJxdPage1;
    }

    @Override
    @DS("dfdz")
    public DadsFsdgdResult queryDadsFsdgdById(String listId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id", listId);
        DadsFsdgd dadsFsdgd = dadsFsdgdMapper.selectOne(queryWrapper);
        if (ObjectUtil.isEmpty(dadsFsdgd)) {
            throw new RuntimeException("查询检修单信息失败！未查询到检修单信息");
        }
        DadsFsdgdResult dadsFsdgdResult = new DadsFsdgdResult();
        BeanUtils.copyProperties(dadsFsdgd, dadsFsdgdResult);
        return dadsFsdgdResult;
    }

    @Override
    @DS("dfdz")
    public DadsJxczbwl queryDadsZbczbwxx(String date, String type, String sbmc, String czmc, String allCheck) {
        List<DispatchOperTickets> czpList = dadsDdrzMapper.getDadsCzpResult(date, sbmc, czmc);
        //String kssj = date + " 00:00:00";
        //String jssj = date + " 23:59:59";

        List<DispatchDefectHandles> sbqxResult = dadsDdrzMapper.getDadsSbqxResult(date, sbmc, czmc);

        Integer ybqxsl = sbqxResult.stream().filter(i -> i.getDispatchLevel() != null && i.getDispatchLevel().contains("一般")).collect(Collectors.toList()).size();
        Integer jjqxsl = sbqxResult.stream().filter(i -> i.getDispatchLevel() != null && i.getDispatchLevel().contains("紧急")).collect(Collectors.toList()).size();
        Integer zdqxsl = sbqxResult.stream().filter(i -> i.getDispatchLevel() != null && i.getDispatchLevel().contains("重大")).collect(Collectors.toList()).size();

        DadsJxczbwl dadsJxczbwl = new DadsJxczbwl();

        List<DadsJwfx> dadsJwfxList = this.queryDadsJxjhResult(date, sbmc, allCheck);
        List<DispatchWayChange> dispatchWayChangeList = new ArrayList<>();
        // 这个地方可能要改
        if (StrUtil.isNotEmpty(czmc)) {
            dadsJwfxList = this.getSbmc(dadsJwfxList, czmc);
        }
        for (DadsJwfx dadsJxjhResult : dadsJwfxList) {
            DispatchWayChange wayChangeMsg = new DispatchWayChange();
            wayChangeMsg.setStatus(dadsJxjhResult.getState());
            wayChangeMsg.setChangeId(String.valueOf(dadsJxjhResult.getId()));
            wayChangeMsg.setEventLevel(dadsJxjhResult.getSjdj());
            wayChangeMsg.setProductName(dadsJxjhResult.getSbmc());
            wayChangeMsg.setStartTime(dadsJxjhResult.getPztdkssj());
            wayChangeMsg.setEndTime(dadsJxjhResult.getPzfdjssj());
            wayChangeMsg.setRisk(dadsJxjhResult.getFxpg());
            dispatchWayChangeList.add(wayChangeMsg);
        }
        dadsJxczbwl.setDispatchWayChangeMsg(dispatchWayChangeList);

        Integer yjfxsl = dadsJwfxList.stream().filter(i -> i.getSjdj() != null && i.getSjdj().equals("一级事件")).collect(Collectors.toList()).size();
        Integer ejfxsl = dadsJwfxList.stream().filter(i -> i.getSjdj() != null && i.getSjdj().equals("二级事件")).collect(Collectors.toList()).size();
        Integer sjfxsl = dadsJwfxList.stream().filter(i -> i.getSjdj() != null && i.getSjdj().equals("三级事件")).collect(Collectors.toList()).size();
        Integer sjsjfxsl = dadsJwfxList.stream().filter(i -> i.getSjdj() != null && i.getSjdj().equals("四级事件")).collect(Collectors.toList()).size();

        Integer jxjhsl = dadsJwfxList.size();

        Date date1 = DateUtil.parse(date, "yyyy-MM-dd");
        String dateStr = DateUtil.format(date1, "yyyy年MM月dd日");
        StringBuilder czslStr = new StringBuilder();
        czslStr.append(dateStr).append(",");
        czslStr.append("操作票数量为").append(czpList.size()).append("个、");
        czslStr.append("检修计划为").append(jxjhsl).append("个、");
        czslStr.append("缺陷处理(一般为").append(ybqxsl).append("个、紧急为").append(jjqxsl).append("个、").append("重大为").append(zdqxsl).append("个)。");
        dadsJxczbwl.setOperTotal(czslStr.toString());

        StringBuilder dwfxStr = new StringBuilder();
        dwfxStr.append(dateStr).append(",");
        dwfxStr.append("电网风险一级事件为").append(yjfxsl).append("个、");
        dwfxStr.append("二级事件为").append(ejfxsl).append("个、");
        dwfxStr.append("三级事件为").append(sjfxsl).append("个、");
        dwfxStr.append("四级事件为").append(sjsjfxsl).append("个。");

        dadsJxczbwl.setGridRisk(dwfxStr.toString());

        if (type.equals("1")) {
            List<DispatchOperTickets> dispatchOperTickets = dadsDdrzMapper.getDadsCzpResult(date, sbmc, czmc);
            dadsJxczbwl.setDispatchOperTickets(dispatchOperTickets);
        } else if (type.equals("3")) {
            List<DispatchDefectHandles> dispatchDefectHandles = dadsDdrzMapper.getDadsSbqxResult(date, sbmc, czmc);
            dadsJxczbwl.setDispatchDefectHandles(dispatchDefectHandles);
        }

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("duty_date", date);
        queryWrapper.orderByDesc("id");
        List<DadsJxczbwxl> dadsJxczbwxl = dadsJxczbwxlMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(dadsJxczbwxl)) {
            dadsJxczbwl.setMemoId(dadsJxczbwxl.get(0).getId());
            dadsJxczbwl.setRemark(dadsJxczbwxl.get(0).getRemark());
            dadsJxczbwl.setDutyDate(dadsJxczbwxl.get(0).getDutyDate());
        } else {
            dadsJxczbwl.setDutyDate(DateUtil.parse(date, "yyyy-MM-dd"));
        }
        return dadsJxczbwl;
    }

    @DS("dfdz")
    private List<DadsJwfx> getSbmc(List<DadsJwfx> dadsJwfxList, String stationName) {
        List<DadsJwfx> dadsJwfxes = new ArrayList<>();
        for (DadsJwfx dadsJwfx : dadsJwfxList) {
            DadsJwfx dadsJwfx1 = new DadsJwfx();
            String czmc = "";
            String sbmc = dadsJwfx.getSbmc();
            String[] strings = new String[]{"500kV", "220kV", "110kV", "35kV", "10kV"};
            for (String string : strings) {
                if (sbmc.startsWith(string)) {
                    sbmc = sbmc.replaceFirst(string, "");
                }
            }
            if (dadsJwfx.getSbmc().indexOf("线") != -1) {
                czmc = dadsDdrzMapper.queryCzmcBySbmcLn(sbmc);
            } else {
                czmc = dadsDdrzMapper.queryCzmcBySbmc(sbmc);
            }
            if (StrUtil.isNotEmpty(czmc) && stationName.contains(czmc)) {
                BeanUtils.copyProperties(dadsJwfx, dadsJwfx1);
                dadsJwfxes.add(dadsJwfx1);
            }
        }
        return dadsJwfxes;
    }

    @Override
    @DS("dfdz")
    public List<DadsJwfx> queryDadsJxjhResult(String date, String sbmc, String allCheck) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.ge("pztdkssj", date + " 00:00:00");
        queryWrapper.le("pzfdjssj", date + " 23:59:59");
        List<DadsJxjh> dadsJxjhList = dadsJxjhMapper.selectList(queryWrapper);
        List<DadsJwfx> dadsJwfxList = new ArrayList<>();
        for (DadsJxjh dadsJxjh : dadsJxjhList) {
            DadsJwfx dadsJwfx = new DadsJwfx();
            BeanUtils.copyProperties(dadsJxjh, dadsJwfx);
            dadsJwfx.setSbmc(dadsJxjh.getTdjxsb());
            dadsJwfx.setJxjhId(dadsJxjh.getId());
            if (StrUtil.isNotEmpty(dadsJxjh.getFxpg())) {
                String pgyjArr[] = dadsJxjh.getFxpg().split(";");
                String sjdj = pgyjArr[0].substring(9, 13);
                dadsJwfx.setSjdj(sjdj);
            }
            try {
                QueryWrapper<DadsJwfx> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("jxjh_id", dadsJwfx.getJxjhId());
                List<DadsJwfx> dadsJwfxList1 = dadsJwfxMapper.selectList(queryWrapper1);
                if (CollectionUtils.isEmpty(dadsJwfxList1)) {
                    dadsJwfxMapper.insert(dadsJwfx);
                } else {
                    dadsJwfx.setId(dadsJwfxList1.get(0).getId());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            dadsJwfxList.add(dadsJwfx);
        }
        QueryWrapper queryWrapper1 = new QueryWrapper();
        queryWrapper1.ge("pztdkssj", date + " 00:00:00");
        queryWrapper1.le("pzfdjssj", date + " 23:59:59");
        if (StrUtil.isNotEmpty(sbmc)) {
            queryWrapper1.like("sbmc", sbmc);
        }
        if (StrUtil.isEmpty(allCheck)) {
            queryWrapper1.isNotNull("sjdj");
        }
        List<DadsJwfx> dadsJwfxList1 = dadsJwfxMapper.selectList(queryWrapper1);
        return dadsJwfxList1;
    }

    @Override
    @DS("dfdz")
    public List<DadsCzpResult> queryDadsCzpResult(String date) {
//        return dadsDdrzMapper.getDadsCzpResult(date);
        return null;
    }

    @Override
    @DS("dfdz")
    public List<DadsSbqxResult> queryDadsSbqxResult(String date) {
//        return dadsDdrzMapper.getDadsSbqxResult(date);
        return null;
    }

    @Override
    @DS("dfdz")
    public boolean insertOrUpdateJxczbwl(DadsJxczbwl dadsJxczbwxl) {
        if (ObjectUtil.isNotEmpty(dadsJxczbwxl.getMemoId()) && dadsJxczbwxl.getMemoId() != 0) {
            DadsJxczbwxl dadsJxczbwxl1 = new DadsJxczbwxl();
            dadsJxczbwxl1.setId(dadsJxczbwxl.getMemoId());
            dadsJxczbwxl1.setRemark(dadsJxczbwxl.getRemark());
            dadsJxczbwxlMapper.updateById(dadsJxczbwxl1);
        } else {
            DadsJxczbwxl dadsJxczbwxl1 = new DadsJxczbwxl();
            dadsJxczbwxl1.setRemark(dadsJxczbwxl.getRemark());
            dadsJxczbwxl1.setDutyDate(dadsJxczbwxl.getDutyDate());
            dadsJxczbwxlMapper.insert(dadsJxczbwxl1);
        }
        if (!CollectionUtils.isEmpty(dadsJxczbwxl.getDispatchWayChangeMsg())) {
            for (DispatchWayChange dispatchWayChange : dadsJxczbwxl.getDispatchWayChangeMsg()) {
                DadsJwfx dadsJwfx = new DadsJwfx();
                dadsJwfx.setId(Integer.valueOf(dispatchWayChange.getChangeId()));
                dadsJwfx.setSjdj(dispatchWayChange.getEventLevel());
                dadsJwfxMapper.updateById(dadsJwfx);
            }
        }
        return true;
    }
}
